Power of Four
LeetCode 342 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4^x.
Example 1:
Input: n = 16
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
- `-2^31 <= n <= 2^31 - 1`
Follow up: Could you solve it without loops/recursion?
Topics: Math, Bit Manipulation, Recursion
Approachβ
Bit Manipulationβ
Operate directly on binary representations. Key operations: AND (&), OR (|), XOR (^), NOT (~), shifts (<<, >>). XOR is especially useful: a ^ a = 0, a ^ 0 = a.
Finding unique elements, power of 2 checks, subset generation, toggling flags.
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 44 ms)β
| Metric | Value |
|---|---|
| Runtime | 44 ms |
| Memory | N/A |
| Date | 2018-04-12 |
public class Solution {
public bool IsPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Bit Manipulation | $O(n) or O(1)$ | $O(1)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.